import React from 'react';
import { Form, Icon, Input, Button, Checkbox } from 'antd';
// import { connect } from 'react-redux';
import api from '../../utils/api';
import storage from '../../utils/storage';
import './style/css/SignIn.less';

const FormItem = Form.Item;

class SignIn extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };

    this.onSignIn = this.onSignIn.bind(this);
    this.onKeyPress = this.onKeyPress.bind(this);
  }

  onKeyPress(e) {
    if (e.charCode !== 13) {
      return;
    }
    this.onSignIn(e);
  }

  onSignIn(e) {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (err) {
        return
      }
      const { username, password } = values;
      api({
        method: 'POST',
        url: '/login/auth',
        data: {
          username,
          password
        },
      }).then((res) => {
        const { code, data } = res.data;
        if (code === 200) {
          storage.set('currentUser', data);
          storage.set('token', data.token);
          this.props.history.push('/');
        }
      });
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="signin">
        <div className="signin-content">
            <div className="form">
              <div className="title">管理后台</div>
              <Form style={{ maxWidth: '300px' }}>
                <FormItem>
                  {getFieldDecorator('username', {
                    rules: [{ required: true, message: '请输入用户名' }],
                  })(
                    <Input prefix={<Icon type="mobile" style={{ fontSize: 13 }} />} placeholder="用户名" onKeyPress={this.onKeyPress} />
                  )}
                </FormItem>
                <FormItem>
                  {getFieldDecorator('password', {
                    rules: [{ required: true, message: '请输入密码' }],
                  })(
                    <Input prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder="密码" onKeyPress={this.onKeyPress} />
                  )}
                </FormItem>
                <FormItem>
                  {getFieldDecorator('remember', {
                    valuePropName: 'checked',
                    initialValue: true,
                  })(
                    <Checkbox>
                      <span className="rember">记住我</span>
                    </Checkbox>
                  )}
                  <span className="forgot">忘记密码</span>
                  <Button type="primary" htmlType="button" className="login-button" onClick={this.onSignIn}>登录</Button>
                </FormItem>
              </Form>
            </div>
        </div>
      </div>
    );
  }
}


export default (Form.create()(SignIn));